#!/bin/bash

DISTRIBUTION_NAME="worker-4.1.5"
DISTRIBUTION_FILE=$DISTRIBUTION_NAME".zip"


# Checks if vmware is installed
function check_vmware_server() {

	vmrun -h https\://localhost\:"$HOST_PORT_NUM"/sdk -u $WORKER_USER -p $WORKER_PASSWD list > /dev/null 2> /dev/null

 	if [ $? -ne 255 ] && [ $? -ne 0 ]; then	
		echo " VMWAre Server is not installed or configured correctly. "
		exit 1
	fi
}

function check_user() {

	su $WORKER_USER -c true
	if  [ $? -ne 0 ] ; then
		echo
		echo "User $WORKER_USER does not exist, you have to create it before installation or select another user." 
		exit 1
	fi
}

function config_Install_Place() {

	# Selecting installation place
	if [ -z "$INSTALATION_DIR" ]; then
		INSTALATION_DIR=`pwd`
	fi

	# Verifying if install directory exists
	echo
	echo "Assigned vserver installation directory: " "$INSTALATION_DIR"
	echo "Verifying if $INSTALATION_DIR exists..."
	ls "$INSTALATION_DIR" > /dev/null 2> /dev/null
	if [ $? -ne 0 ]; then
		echo
		echo "Directory $INSTALATION_DIR not exists..."
		echo "Creating directory $INSTALATION_DIR..."
		mkdir -p "$INSTALATION_DIR "
	fi
	
	echo "OK"
}

function extracting_distribution() {

	unzip "$DISTRIBUTION_FILE" -d "$INSTALATION_DIR"

	if [ ! $? ] ; then
		echo " An error ocurred on extraction of the distribution, the installation could not be done."
		exit 1
	fi
}

function copy_vmware_scripts() {
	
	echo "Copying VMware scripts to $INSTALATION_DIR/$DISTRIBUTION_NAME ..."

	cp -r vmware_scripts "$INSTALATION_DIR/$DISTRIBUTION_NAME"

}

function config_logDir() {

	LOG_DIR="$INSTALATION_DIR/$DISTRIBUTION_NAME/logs"	
	
	echo
	echo "Verifying if $LOG_DIR exists..."

	ls -la $LOG_DIR &> /dev/null
	if [ $? -ne 0 ]; then
        	echo
		echo "Directory $LOG_DIR not exists..."
		echo "Creating directory $LOG_DIR..."
		mkdir "$LOG_DIR"
	fi

}

# Configure VMWare
function config_vmware() {

	# Ask the user for some properties of vmware
	echo 
	echo "=================================="
	echo "Configuring the VMWare Properties"
	echo "=================================="

	if [ -z "$DATASTORE_NAME" ] ; then
		echo
		echo "What's the VMWare DataStore name?"
		read DATASTORE_NAME
	fi

	if [ -z $HOST_PORT_NUM ] ; then
		echo
		echo "What's the VMWare port number?"
		read HOST_PORT_NUM
	fi

}

#Extract the Virtual Machine on DataStore
function extract_virtual_machine() {

	echo
	echo "Extracting the Virtual Machine file, this may take several minutes..."

	propeller &
	PID=$!

	tar -jxvf "linux-vmware_20081223.tar.bz2" -C "$DATASTORE_PATH"
	EXIT=$?        
                                
	kill -9 $PID > /dev/null 2> /dev/null
	if [ $EXIT -ne 0 ] ; then
		echo " An error ocurred on extraction of the virtual machine, the installation could not be done."
		exit 1
	fi
}

function propeller() {
	
	while :
	do
		for i in / - \\ \|
		do
			sleep .1
			echo -ne "\e[D$i"
		done
	done
}

# Register the Virtual Machine
function register_VM() {
	
	echo
	echo "==============================================="
	echo " 	      Registering Virtual Machine ...        "
	echo "==============================================="
	
	#Command to register the Virtual Machine
	vmrun -h https\://localhost\:"$HOST_PORT_NUM"/sdk -u $WORKER_USER -p $WORKER_PASSWD register "[$DATASTORE_NAME] debian/debian.vmx" > /dev/null 2> /dev/null
	
	if [ $? -ne 0 ] ; then
		echo " An error ocurred in the virtual machine registration, the registration could not be done."
		exit 1
	fi
}

# Configure the debian.vmx file
function configure_vmxfile() {

	sed -i '/ethernet0.startConnected = "FALSE"/a \uuid.action = "create"' "$DATASTORE_PATH/debian/debian.vmx"

}

# Configure the properties of worker
function config_worker_properties() {

	WORKER_PROPERTIES="$INSTALATION_DIR/$DISTRIBUTION_NAME/worker.properties"
	
	ls -la "$WORKER_PROPERTIES" &> /dev/null
	if [ ! $? ] ; then
		echo " An error ocurred on configuration of the worker properties. The file [$WORKER_PROPERTIES] does not exist. The installation could not be done."
		exit 1
	fi

	# Ask the user for some properties of worker
	echo 
	echo "=================================="
	echo "Configuring the Worker Properties "
	echo "=================================="

	answer=
	echo
	echo "What's the user's name of worker on XMPP server? "
	read answer
	echo "commune.xmpp.username="$answer > "$WORKER_PROPERTIES"

	echo
	echo "What's the name of XMPP server that worker will connect? "
	read answer
	echo "commune.xmpp.servername="$answer >> "$WORKER_PROPERTIES"

	echo
	echo "What's the user's password of worker on XMPP server? "
	read answer
	echo "commune.xmpp.password="$answer >> "$WORKER_PROPERTIES"

	echo
	echo "Do you wish enable the idleness detector? [yes/no] "
	read answer
	echo "worker.idlenessdetector="$answer >> "$WORKER_PROPERTIES"

	answer=`echo $answer | tr '[:upper:]' '[:lower:]'`

	if [ $answer = "yes" -o $answer = "y" ]; then
		echo
		echo "How many seconds for detection of idleness?"
		read answer
		echo "worker.idlenesstime="$answer >> "$WORKER_PROPERTIES"
	fi
	
	# The property "worker.peer.publickey" must be configured manually
	echo "worker.peer.publickey=" >> "$WORKER_PROPERTIES"

	# Configure the worker's properties to use vserver executor
	echo "worker.executor=VMWARE" >> "$WORKER_PROPERTIES"
	echo "worker.VM_HOST_USER="$WORKER_USER >> "$WORKER_PROPERTIES"
	echo "worker.VM_HOST_PASSWD="$WORKER_PASSWD >> "$WORKER_PROPERTIES"
	echo "worker.VM_GUEST_USER=root" >> "$WORKER_PROPERTIES"
	echo "worker.VM_GUEST_PASSWD=root" >> "$WORKER_PROPERTIES"
	echo "worker.STORAGE_DIR_IN_VM=/tmp/vm/storage" >> "$WORKER_PROPERTIES"
	echo "worker.PLAYPEN_DIR_IN_VM=/tmp/vm/playpen" >> "$WORKER_PROPERTIES"
	echo "worker.VM_IMAGE_PATH=[$DATASTORE_NAME] debian/debian.vmx" >> "$WORKER_PROPERTIES"
	echo "worker.VM_HOST_ADDRESS=https\://localhost\:"$HOST_PORT_NUM"/sdk" >> $WORKER_PROPERTIES

}

function usage() {

	# Diretorio onde está a disco virtual vmx
	echo "Usage: build-og-vmware <installationDir> <workerAccountUserName> <workerAccountUserPassword> <hostPortNumber> <dataStorePath> [ <dataStoreName> ]"
	echo "For OurGrid updates and additional information, see the "
	echo "OurGrid Project home page at http://www.ourgrid.org/ "
}

# main() - Checking for dependencies.

# Assign the variables
nargs=$#

if [ $nargs -ge 5 ]; then
	INSTALATION_DIR=$1
	WORKER_USER=$2
	WORKER_PASSWD=$3
	HOST_PORT_NUM=$4
	DATASTORE_PATH=$5
	DATASTORE_NAME=$6
else 
	usage
	exit 1
fi


echo
echo "================================="
echo "   Ready to begin installation   "
echo "================================="

echo -n "Checking for vmware ... "
check_vmware_server
echo "OK"
echo

echo "Assigned vmware host user name: " $WORKER_USER
check_user

# main() - Installing Worker
echo
echo "======================="
echo "   Installing Worker   "
echo "======================="
echo
echo "Installing the OurGrid Worker"

config_Install_Place
extracting_distribution
copy_vmware_scripts
config_logDir
config_vmware
extract_virtual_machine
register_VM
configure_vmxfile
config_worker_properties


# Changing the owner of worker dir
chown $WORKER_USER -R $INSTALATION_DIR
# Setting the worker binary as executable
chmod 744 "$INSTALATION_DIR/$DISTRIBUTION_NAME/worker"
cd "$INSTALATION_DIR/$DISTRIBUTION_NAME/vmware_scripts"
chmod 744 *

echo
echo "====================================="
echo "   You're done. Worker is installed."
echo "====================================="
echo 
